package com.cloudoer.blog.service.impl;

import com.cloudoer.blog.base.BaseService;
import com.cloudoer.blog.exception.ServiceException;
import com.cloudoer.blog.model.Photo;
import com.cloudoer.blog.service.PhotoService;
import com.cloudoer.blog.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service(value = "photoService")
public class PhotoServiceImpl extends BaseService implements PhotoService {

    @Autowired
    private FileUtil fileUtil;

    @Override
    public Photo getById(String id) {
        return photoDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Photo> getByPage(String albunId, int pstart, int psize) {
        return photoDao.selectByPage(albunId, pstart, psize);
    }

    @Override
    public List<Photo> getAll(String albunId) {
        return photoDao.selectAll(albunId);
    }

    @Override
    public String add(MultipartFile multipartFile, String albumId) throws ServletException, IOException {
        MultipartFile multipartFile1 = multipartFile;
        Photo photo = new Photo();
        String id = UUID.randomUUID().toString().replace("-", "");
        photo.setId(id);
        photo.setPostDate(new Date());
        photo.setName(multipartFile.getOriginalFilename());
        photo.setAlbunId(albumId);
        String url = fileUtil.uploadFile(multipartFile, albumId, id);
        photo.setUrl(url);
        String subUrl = fileUtil.compressImg(url, albumId, UUID.randomUUID().toString().replace("-", ""));
        photo.setSubUrl(subUrl);
        photoDao.insertSelective(photo);
        return photo.getId();
    }

    @Override
    public int update(Photo photo) {
        return photoDao.updateByPrimaryKeySelective(photo);
    }

    @Override
    public int delete(String id) {
        Photo photo = photoDao.selectByPrimaryKey(id);
        if (photo == (null)){
            throw new ServiceException("已经不存在");
        }
        fileUtil.deleteFileByURL(photo.getUrl());
        fileUtil.deleteFileByURL(photo.getSubUrl());
        return photoDao.deleteByPrimaryKey(id);
    }

    @Override
    public int getCount() {
        return photoDao.getCount();
    }
}
